//
//  SearchViewController.m
//  WonderfulNotes
//
//  Created by 千锋 on 16/1/19.
//  Copyright © 2016年 andy. All rights reserved.
//

#import "SearchViewController.h"
#import "NoteCell.h"
#import "NoteModel.h"
#import "UIColor+LNHex.h"
#import "iflyMSC/IFlyMSC.H"
#import "WriteViewController.h"
static const CGFloat ToolBarHeight = 44;
@interface SearchViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchResultsUpdating,IFlyRecognizerViewDelegate>
{
    UITableView * _tableView;
    NSMutableArray * _filterArray;// 存储过滤后的数据
    NSArray * _dataArr;
    UISearchController * _searchController;
    
    //界面识别语音
    IFlyRecognizerView *_iflyRecongizerView;
    NSMutableString *_resultTitleString;
    UIView *_currentActiveTF;
    NSInteger _index;
    
}

@property (nonatomic,strong) NSMutableArray * allData; //数据源

@end

@implementation SearchViewController

-(NSMutableArray *)allData{
    
    if (_allData==nil) {
        
        _allData = @[].mutableCopy;
    }
    return _allData;
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self createTableView];
    [self dataDealwith];
    [self createSearchController];
    [self setupVoiceRecongizerView];

    [_tableView registerNib:[UINib nibWithNibName:@"NoteCell" bundle:nil] forCellReuseIdentifier:@"NoteCell"];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)createTableView{
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 65, SCREEN_WIDTH, SCREEN_HEIGHT-65)];
    [self.view addSubview:_tableView];
    _tableView.delegate =self;
    _tableView.dataSource = self;

}

-(void)dataDealwith{
    
    //数据处理
    for (NoteModel * model in self.dataArray) {
        
        [self.allData addObject:model.noteTitle];
    }
    
}

-(void)createSearchController{
    
    UIBarButtonItem * doneBtn = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(hideKeyboard)];
    doneBtn.width = ceilf(SCREEN_WIDTH)/3-30;
    UIBarButtonItem * voiceBtn = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"voice"] style:UIBarButtonItemStylePlain target:self action:@selector(userVoiceINput1)];
    voiceBtn.width = ceilf(SCREEN_WIDTH)/2-50;
    UIToolbar * toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ToolBarHeight)];
    toolBar.tintColor = [UIColor systemColor];
    toolBar.items = [NSArray arrayWithObjects:doneBtn,voiceBtn, nil];
    
    _searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
    //更新数据代理
    _searchController.searchBar.placeholder = @"笔记标题或内容";
    _searchController.searchResultsUpdater = self;
    _searchController.dimsBackgroundDuringPresentation = NO;
    _tableView.tableHeaderView = _searchController.searchBar;
  //  _searchController.searchBar.inputAccessoryView =toolBar;
    _searchController.searchBar.delegate = self;
    _searchController.searchBar.showsCancelButton = YES;
    [_searchController.searchBar sizeToFit];

}

#pragma mark - 键盘隐藏

-(void)hideKeyboard{
    
    if ([_searchController.searchBar isFirstResponder]) {
        [_searchController.searchBar resignFirstResponder];
    }
}

-(void)userVoiceINput1{
    
    _resultTitleString = [NSMutableString string];
    [_iflyRecongizerView start];
    [self hideKeyboard];
}

#pragma mark - UITableViewDataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (_searchController.active) {
       return _filterArray.count;
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell==nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    }
    cell.textLabel.text = _allData[_index];
    
    return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    [self hideKeyboard];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    for (NoteModel * model in self.dataArray) {
        
        if ([model.noteTitle isEqualToString:_filterArray[indexPath.row]]) {
            _index = [self.dataArray indexOfObject:model];
            
        }
    }
    
    WriteViewController * writeVC = [[WriteViewController alloc]init];
    
    NoteModel * model = self.dataArray[_index];
    
    writeVC.noteTitle = model.noteTitle;
    writeVC.noteText = model.noteText;
    writeVC.noteImage = model.noteUrlArr;
    UINavigationController* nv = [[UINavigationController alloc]initWithRootViewController:writeVC];
    [self presentViewController:nv animated:YES completion:nil];
 
   // [self presentViewController:writeVC animated:YES completion:nil];
    
}

#pragma mark -搜索框代理回调

-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",searchController.searchBar.text];
    _filterArray = [self.allData filteredArrayUsingPredicate:predicate].copy;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [_tableView reloadData];
        
    });

}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    
    searchBar.text=nil;
    
    [_searchController.searchBar resignFirstResponder];
    
    
}



#pragma mark -语音读取功能

-(void)setupVoiceRecongizerView{
    
    //语音识别界面弹出点
    _iflyRecongizerView = [[IFlyRecognizerView alloc]initWithCenter:self.view.center];
    _iflyRecongizerView.delegate = self;
    //公共参量，应用领域
    [_iflyRecongizerView setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
    //数据返回的类型，默认为json
    [_iflyRecongizerView setParameter:@"plain" forKey:[IFlySpeechConstant RESULT_TYPE]];
    _resultTitleString = [NSMutableString string];
    
}

#pragma mark -IFlyRecognizerViewDelegate->语音转换问文字

-(void)onResult:(NSArray *)resultArray isLast:(BOOL)isLast{
    
    NSMutableString * result = [[NSMutableString alloc]init];
    NSDictionary * dic = [resultArray objectAtIndex:0];
    for (NSString * key in dic) {
        [result appendFormat:@"%@",key];
    }
    [_resultTitleString appendString:result];
    
    NSLog(@"-----------%@",_resultTitleString);
  
    if (isLast) {
    
        _searchController.searchBar.text = _resultTitleString;

    }
    
}

-(void)onError:(IFlySpeechError *)error{
    
    NSLog(@"错误码:%d",[error errorCode]);
    NSLog(@"错误描述:%@",[error errorDesc]);
    NSLog(@"错误码类:%d",[error errorType]);
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
